package com.tiepbm.cucphamgiadinh.fragment;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;

import com.tiepbm.cucphamgiadinh.R;
import com.tiepbm.cucphamgiadinh.activity.MyApp;

public class FragmentDetail extends Fragment {

	private WebView webView;
	private int pos;

	public static FragmentDetail newInstance(int pos) {
		FragmentDetail fragment = new FragmentDetail();
		fragment.pos = pos;

		return fragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if ((savedInstanceState != null)
				&& savedInstanceState.containsKey("pos")) {
			pos = savedInstanceState.getInt("pos");
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		ViewGroup view = (ViewGroup) inflater.inflate(R.layout.fragment_detail,
				null);
		webView = (WebView) view.findViewById(R.id.webView1);
		WebSettings webSettings = webView.getSettings();
		webSettings.setDefaultFontSize(MyApp.textSize);
		fillWebView(pos);
		return view;
	}

	private String loadAssetTextAsString(Context context, String name) {
		BufferedReader in = null;
		try {
			StringBuilder buf = new StringBuilder();
			InputStream is = context.getAssets().open(name);
			in = new BufferedReader(new InputStreamReader(is));
			String str;
			boolean isFirst = true;

			while ((str = in.readLine()) != null) {
				if (isFirst)
					isFirst = false;
				else
					buf.append("<br>");
				buf.append(str);
			}
			return buf.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
				}
			}
		}

		return null;
	}

	private void fillWebView(int pos) {
		String html = loadAssetTextAsString(getActivity(), "cpgd/" + pos
				+ ".txt");
		if (html != null) {
			String customHtml = "<html><head><META http-equiv=Content-Type content =\"text/html; charset=utf-8\"></head> <body style=\"text-align:justify\">"
					+ html + "</body></html>";
			webView.loadDataWithBaseURL("", customHtml, "text/html", "UTF-8",
					"");
		} else {
			Toast.makeText(getActivity(), "Nội dung đang được cập nhật.",
					Toast.LENGTH_SHORT).show();
		}
	}
	public void changeTextSize(){
		MyApp.textSize = MyApp.textSize+2;
		webView.getSettings().setDefaultFontSize(MyApp.textSize);
	}
}
